import { ref } from "vue";
import modelExtends from "./modelTypeExtend.js";

export function dataModels(meta, vm) {
  const { ns, module, alias, parentAlias, childField, modelType } = meta;

  const dm = ref({
    "vm": vm,
    "ns": ns,
    "module": module,
    "name": alias,
    "parent": parentAlias,
    "mode": vm.mode,
    childField,
    modelType,
    "data": {

    },
    "methods": {
      "setData": function (data) {
        throw "'setData'方法未实现！";
      }, "getData": function () {
        return dm.value.data;
      }
    },
    "exec": function (name, args) {
      let callback = this.methods[name];
      if (callback) {
        return callback(args);
      } else {
        console.warn('找不到方法：' + name)
      }
    },
    "setMethod": (name, handler) => {
      dm.value.methods[name] = handler;
    },
    "getMethod": (name) => {
      return dm.value.methods[name];
    }
  });
  if (modelExtends[modelType]) {
    modelExtends[modelType](dm);
  }
  return dm;
}

export function createModel(vm) {
  const models = {
    "$items": [

    ]
  };
  const modelDefs = vm.META?.modelNew;
  if (modelDefs) {
    let defaultAlias;
    modelDefs.forEach(x => {
      let m = dataModels(x, vm);
      models.$items.push(m);
      models[x.alias] = m;
      if (x.isDefault == true) {
        defaultAlias = x.alias;
      }
    });
    models.defaultModel = defaultAlias;
  }
  return models;
}

export function gridModel(vm) {
  const $thiz = ref({
    filterModel: ref({

    }),
    getSelectedRows: function () {
      if (this.$ref) {
        let rows = this.$ref.getSelectionRows();
        return rows;
      }
      return [];
    },
    setDs: function (ds) {
      let data = $thiz.value;
      data.pageIndex = ds.pageIndex;
      data.pageSize = ds.pageSize;
      data.total = ds.total;
      data.rows = ds.rows;
      $thiz.value = data;
    }
  });
  return $thiz;
}